package controllers

import (
	"doctor/models"
	"doctor/util"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	lockkey := "lock-" + username
	countkey := "count" + username
	num, _ := models.Rdb.Exists(lockkey).Result()
	if num > 0 {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "账号锁定",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "用户名错误",
			Data: nil,
		}
		c.ServeJSON()
	}
	if user.Password == util.MD5Pwd(password) {
		models.Rdb.Del(lockkey)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "登录成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		count, _ := models.Rdb.Get(countkey).Result()
		if count > "3" {
			models.Rdb.Set(lockkey, "locked", time.Hour*24)
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "密码错误",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
	}

}
